<template>
  <div>
    <a-space>
      <!-- table style -->
      <a-dropdown v-if="!sizeHide" :trigger="['click']">
        <a-button
          type="dashed"
          shape="circle"
          icon="column-height" />
        <a-menu slot="overlay" :selected-keys="[tableSize]" @click="changeSize">
          <a-menu-item key="default">
            默认
          </a-menu-item>
          <a-menu-item key="middle">
            中等
          </a-menu-item>
          <a-menu-item key="small">
            紧凑
          </a-menu-item>
        </a-menu>
      </a-dropdown>
      <a-popover v-if="!settingHide" placement="bottomRight" trigger="click">
        <template slot="content">
          <a-tree
            class="draggable-tree"
            :show-icon="true"
            v-model="checkedKeys"
            checkable
            :replaceFields="replaceFields"
            draggable
            :tree-data="currentValue"
            @drop="onDrop"
          />
        </template>
        <!-- 列展示/排序 -->
        <template slot="title">
          <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">
            列展示/排序
            <a-tooltip>
              <template slot="title">
                列排序需拖动名称
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </a-checkbox>
        </template>
        <a-button
          type="dashed"
          shape="circle"
          icon="setting" />
      </a-popover>
      <!-- 视图 -->
      <a-popover v-if="!settingHide" placement="bottomRight" trigger="click">
        <a-button
          type="dashed"
          shape="circle"
          icon="book" />
        <template slot="title">
          <a-button @click="addItem">新增</a-button>
          <a-button @click="saveLocal">本地保存</a-button>
          <a-button @click="saveLocal">远程保存</a-button>
        </template>
        <template slot="content">

          <a-checkbox-group>
            <a-row
              v-for="item in items"
              :key="item.id">
              <template v-if="!item.isEdit">
                <a-space direction="vertical">
                  <a-row :gutter="24">
                    <a-col :span="18">
                      <a-checkbox :value="item" >{{ item.name }}</a-checkbox>

                    </a-col>
                    <a-col :span="4">
                      <a-space direction="horizontal" align="center">
                        <a type="primary" @click="deitData(item)" shape="circle" >
                          <a-icon type="edit" />
                        </a>
                        <a type="danger" @click="deleteData(item)" shape="circle">
                          <a-icon type="delete" />
                        </a>
                      </a-space>
                    </a-col>
                  </a-row>

                </a-space>

              </template>
              <template v-else>

                <a-space direction="vertical">
                  <a-row :gutter="24">
                    <a-col :span="12">
                      <a-input v-model="item.name"></a-input>
                    </a-col>
                    <a-col :span="8">
                      <a-space direction="horizontal" align="center">
                        <a-button type="primary" @click="saveData(item)">保存</a-button>
                        <a-button type="danger" @click="deleteData(item)">删除</a-button>
                      </a-space>
                    </a-col>
                  </a-row>
                </a-space>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>

      </a-popover>
      <!-- 组合 -->
      <a-popover content="" title="">
        <a-button
          type="dashed"
          shape="circle"
          icon="appstore" />
      </a-popover>
      <!-- refresh -->
      <a-button
        type="dashed"
        shape="circle"
        v-if="!refreshHide"
        :loading="refreshLoading"
        icon="reload"
        @click="refresh" />
    </a-space>
  </div>
</template>

<script>
import Ellipsis from '@/components/Ellipsis'
import { mapGetters } from 'vuex'
// import { cloneDeep } from 'lodash'

let index = 0
export default {
  name: 'NumberInfo',
  props: {
    tableSize: {
      type: String,
      default: 'default'
    },
    refreshLoading: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      required: true
    },
    refreshHide: {
      type: Boolean,
      default: false
    },
    settingHide: {
      type: Boolean,
      default: false
    },
    sizeHide: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Ellipsis,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  data () {
    return {
      allKey: [],
      indeterminate: true,
      checkAll: false,
      currentValue: [],
      checkedKeys: [],
      replaceFields: { children: 'children', title: 'currentTitle', key: 'dataIndex', slot: 'tsSlots' },
      items: [],
      viewsData: {}
    }
  },
  computed: {
     ...mapGetters([
      'avatar',
      'nickname',
      'userId'
    ])
  },
  mounted () {
    this.currentValue = this.value
    const localData = JSON.parse(localStorage.getItem(this.userId))
    const currentHistory = localData[this.$route.name]
    if (currentHistory) {
      console.info(currentHistory)
    }
    this.currentValue.forEach(column => {
      this.allKey.push(column.dataIndex)
      column.currentTitle = <ellipsis length={16} tooltip>{column.title}</ellipsis>
      column.width2 = column.width
      column.ellipsis2 = column.ellipsis
      if (column.width !== 0 || !column.ellipsis) {
          this.checkedKeys.push(column.dataIndex)
        }
      const tmp = currentHistory.filter(it => it.dataIndex === column.dataIndex)[0]

      if (tmp && tmp.width === 0) {
        // this.checkedKeys.push(column.dataIndex)
        column.width = 0
      }

      column.switcherIcon = <a-icon type="pic-left" />
      console.info(column, '4444')
    })
  },
  watch: {
    checkedKeys (cur, last) {
      const checked = cur.filter(function (v) { return last.indexOf(v) === -1 })
      const canceled = last.filter(function (v) { return cur.indexOf(v) === -1 })
      this.currentValue.forEach(column => {
        if (checked.length > 0) {
          if (checked.indexOf(column.dataIndex) > -1) {
            this.$set(column, 'width', column.width2)
            this.$set(column, 'ellipsis', column.ellipsis2)
          }
        } else if (canceled.length > 0) {
          if (canceled.indexOf(column.dataIndex) > -1) {
            this.$set(column, 'width', 0)
            this.$set(column, 'ellipsis', true)
          }
        }
      })
      this.indeterminate = !!cur.length && cur.length < this.allKey.length
      this.checkAll = cur.length === this.allKey.length
      console.info(this.currentValue, this.value)
      this.$emit('input', this.currentValue)
    }
  },
  methods: {
    saveLocal () {
      // 本地保存，定义结构
      /**
       key：userId

       value： {
       userId: 1,
       tableSetting:[
        {
          '/a/b/c':[
            {视图对象一},
            {视图对象二},
            {视图对象三},
          ]
        }
        ]
       }
       */
      // const path = this.$route.name
      // this.viewsData = {
      //   userId: this.userId,
      //   tableSetting: {
      //     path: this.items
      //   }
      // }

      if (!this.viewsData[this.$route.name]) {
        this.$set(this.viewsData, this.$route.name, this.items)
      }
      console.info(this.userId, this.viewsData, this.items, 'text')
      localStorage.setItem(this.userId, JSON.stringify(this.viewsData, (key, value) => {
        console.info(key, value, '3333')
        if (key === 'componentOptions' || key === 'context' || key === 'data' || key === 'switcherIcon' || key === 'effects') {
          return ''
        }
        return value
      }))
    },
    addItem () {
      console.log('addItem')
      this.items.push({ id: new Date().getTime(), name: `试图 ${index++}`, isEdit: true, column: this.value })
    },
    saveData (item) {
      this.items.filter(it => it.id === item.id)[0].isEdit = false
    },
    deitData (item) {
      item.isEdit = true
    },
    deleteData (item) {
      this.items = this.items.filter(it => it.id !== item.id)
    },
    changeSize (e) {
      this.$emit('update:tableSize', e.key)
    },
    onCheckAllChange (e) {
      Object.assign(this, {
        checkedKeys: e.target.checked ? this.allKey : [],
        indeterminate: false,
        checkAll: e.target.checked
      })
    },
    refresh () {
      this.$emit('refresh')
    },
    onDrop (info) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.dataIndex === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.value]

      // Find dragObject
      let dragObj
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1)
        dragObj = item
      })
      let ar
      let i
      loop(data, dropKey, (item, index, arr) => {
        ar = arr
        i = index
      })
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj)
      } else {
        ar.splice(i + 1, 0, dragObj)
      }
      this.$emit('input', data)
      this.currentValue = data
    }
  }
}
</script>
